package com.example.component;

import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseEvent;
import javafx.util.StringConverter;

public class CustomTextFieldTableCell<S, T> extends TextFieldTableCell<S, T> {
    private TextField textField;

    public CustomTextFieldTableCell(StringConverter<T> converter) {
        super(converter);

        // 添加双击事件监听
        this.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            if (event.getClickCount() == 2 && !isEditing()) {
                startEdit();
                event.consume();
            }
        });
    }

    @Override
    public void startEdit() {
        super.startEdit();
        if (isEditing()) {
            createTextField();
        }
    }

    private void createTextField() {
        if (textField == null) {
            textField = new TextField(getString());
            textField.setEditable(true);
            
            // 处理按键事件
            textField.setOnKeyPressed(event -> {
                if (event.getCode() == KeyCode.ENTER) {
                    commitEdit(getConverter().fromString(textField.getText()));
                    event.consume();
                } else if (event.getCode() == KeyCode.ESCAPE) {
                    cancelEdit();
                    event.consume();
                }
            });

            // 处理失焦事件
            textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
                if (!isNowFocused && isEditing()) {
                    commitEdit(getConverter().fromString(textField.getText()));
                }
            });
        }

        textField.setText(getString());
        setText(null);
        setGraphic(textField);
        
        textField.requestFocus();
        textField.selectAll();
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        setText(getString());
        setGraphic(null);
    }

    @Override
    public void commitEdit(T newValue) {
        super.commitEdit(newValue);
        setText(getString());
        setGraphic(null);
    }

    @Override
    public void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            if (isEditing()) {
                setText(null);
                setGraphic(textField);
            } else {
                setText(getString());
                setGraphic(null);
            }
        }
    }

    private String getString() {
        return getItem() == null ? "" : getItem().toString();
    }
} 